package com.whalehearing.tingyou.api.controller.hearing;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.whalehearing.tingyou.common.core.controller.BaseController;
import com.whalehearing.tingyou.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阿里云听力文件地址Controller
 *
 * @author zengjun-qxm
 * @date 2024-09-11
 */
@Api(tags = "api听力检测管理")
@RestController
@RequestMapping("/api/hearing/hearingTest-ccc")
public class ApiHearingOssFileController extends BaseController {


    /**
     * 获取【项目中】所有听力检测音频文件
     */
    @ApiOperation("查询项目中用于-听力检测-的音频文件")
    @GetMapping("/getAllAudioFiles")
    public AjaxResult listAudioFiles() throws IOException {
        String basePath = "tingyou-admin/src/main/resources/audio";
        Map<String, Object> result = new HashMap<>();

        // 将 hearing_test 和 speech_test 文件分别放入结果集
        result.put("hearing_test", getHearingTestFiles(basePath + "/hearing_test"));
        result.put("speech_test", getSpeechTestFiles(basePath + "/speech_test"));

        return AjaxResult.success(result);
    }

    // 遍历 hearing_test 目录下的文件（包括 left_ear 和 right_ear）
    private Map<String, Object> getHearingTestFiles(String hearingTestPath) throws IOException {
        Map<String, Object> hearingTestMap = new HashMap<>();

        // 获取 left_ear 和 right_ear 文件夹的音频，且排除空的耳朵文件夹
        Map<String, List<String>> leftEarFiles = getEarAudioFiles(hearingTestPath + "/left_ear");
        if (!leftEarFiles.isEmpty()) {
            hearingTestMap.put("left_ear", leftEarFiles);
        }

        Map<String, List<String>> rightEarFiles = getEarAudioFiles(hearingTestPath + "/right_ear");
        if (!rightEarFiles.isEmpty()) {
            hearingTestMap.put("right_ear", rightEarFiles);
        }

        return hearingTestMap;
    }

    // 获取指定耳朵文件夹中的音频文件
    private Map<String, List<String>> getEarAudioFiles(String earPath) throws IOException {
        Map<String, List<String>> earAudioFiles = new HashMap<>();

        // 遍历耳朵文件夹内的子文件夹
        Files.walk(Paths.get(earPath), 1).filter(Files::isDirectory).forEach(subDir -> {
            try {
                String dirName = subDir.getFileName().toString(); // 获取子文件夹名
                List<String> audioFiles = new ArrayList<>();

                // 遍历文件夹内的所有音频文件
                Files.walk(subDir, 1).filter(Files::isRegularFile).forEach(audioFile -> {
                    String fullPath = audioFile.toAbsolutePath().toString();
                    audioFiles.add(fullPath); // 添加完整文件路径到列表
                });

                // 仅当音频文件列表不为空时才将其加入到 Map
                if (!audioFiles.isEmpty()) {
                    earAudioFiles.put(dirName, audioFiles);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        return earAudioFiles;
    }

    // 获取 speech_test 目录下的音频文件
    private List<String> getSpeechTestFiles(String speechTestPath) throws IOException {
        List<String> speechTestFiles = new ArrayList<>();

        // 遍历 speech_test 文件夹下的所有音频文件
        Files.walk(Paths.get(speechTestPath), 1).filter(Files::isRegularFile).forEach(audioFile -> {
            String fullPath = audioFile.toAbsolutePath().toString();
            speechTestFiles.add(fullPath); // 添加完整文件路径到列表
        });

        return speechTestFiles;
    }


    /**
     * 获取【阿里云oss】所有听力检测音频文件
     */
    private static final String ACCESS_KEY_ID = "LTAI5tJ5gGCEFgwcbkJpX7t9";
    private static final String ACCESS_KEY_SECRET = "bQHdCvL4MoqERhtktawJYaTWrIROXm";
    private static final String ENDPOINT = "oss-cn-shenzhen.aliyuncs.com";
    private static final String BUCKET_NAME = "tingyou-jtdymt";
    private static final String DOMAIN = "https://tingyou-jtdymt.oss-cn-shenzhen.aliyuncs.com/";

    @ApiOperation("查询【阿里云oss】听力文件地址列表")
    @GetMapping("/getOssAllAudioFiles")
    public AjaxResult getOssAllAudioFilesNew() {
        Map<String, Object> result = new HashMap<>();

        // 将 hearing_test 和 speech_test 文件分别放入结果集
        result.put("speech_test", getSpeechTestFiles());
        result.put("hearing_test", getHearingTestFiles());

        return AjaxResult.success(result);
    }

    private List<String> getSpeechTestFiles() {
        String prefix = "audio/speech_test/";
        List<String> audioFileUrls = listAudioFiles(prefix);
        return audioFileUrls;
    }

    // 查询 hearing_test 目录下的文件（包括 left_ear 和 right_ear）
    private Map<String, Object> getHearingTestFiles() {
        Map<String, Object> hearingTestMap = new HashMap<>();
        // 获取 left_ear 和 right_ear 以及，隐蔽音频，文件夹的音频
        hearingTestMap.put("left_ear", leftEarFiles());
        hearingTestMap.put("mask_left_ear", maskLeftEar());
        hearingTestMap.put("right_ear", rightEarFiles());
        hearingTestMap.put("mask_right_ear", maskRightEar());
        return hearingTestMap;
    }

    //左耳音频列表
    private Map<String, Object> leftEarFiles() {
        Map<String, Object> hearingTestMap = new HashMap<>();
        // 获取 left_ear 所有音频列表
        hearingTestMap.put("125Hz", listAudioFiles("audio/hearing_test/left_ear/125Hz/"));
        hearingTestMap.put("250Hz", listAudioFiles("audio/hearing_test/left_ear/250Hz/"));
        hearingTestMap.put("500Hz", listAudioFiles("audio/hearing_test/left_ear/500Hz/"));
        hearingTestMap.put("750Hz", listAudioFiles("audio/hearing_test/left_ear/750Hz/"));
        hearingTestMap.put("1000Hz", listAudioFiles("audio/hearing_test/left_ear/1000Hz/"));
        hearingTestMap.put("1500Hz", listAudioFiles("audio/hearing_test/left_ear/1500Hz/"));
        hearingTestMap.put("2000Hz", listAudioFiles("audio/hearing_test/left_ear/2000Hz/"));
        hearingTestMap.put("3000Hz", listAudioFiles("audio/hearing_test/left_ear/3000Hz/"));
        hearingTestMap.put("4000Hz", listAudioFiles("audio/hearing_test/left_ear/4000Hz/"));
        hearingTestMap.put("6000Hz", listAudioFiles("audio/hearing_test/left_ear/6000Hz/"));
        hearingTestMap.put("8000Hz", listAudioFiles("audio/hearing_test/left_ear/8000Hz/"));
        hearingTestMap.put("12500Hz", listAudioFiles("audio/hearing_test/left_ear/12500Hz/"));
        return hearingTestMap;
    }

    //左耳隐蔽音频列表
    private Map<String, Object> maskLeftEar() {
        Map<String, Object> hearingTestMap = new HashMap<>();
        // 获取 left_ear 所有音频列表
        hearingTestMap.put("125Hz", listAudioFiles("audio/hearing_test/mask_left_ear/125Hz/"));
        hearingTestMap.put("250Hz", listAudioFiles("audio/hearing_test/mask_left_ear/250Hz/"));
        hearingTestMap.put("500Hz", listAudioFiles("audio/hearing_test/mask_left_ear/500Hz/"));
        hearingTestMap.put("750Hz", listAudioFiles("audio/hearing_test/mask_left_ear/750Hz/"));
        hearingTestMap.put("1000Hz", listAudioFiles("audio/hearing_test/mask_left_ear/1000Hz/"));
        hearingTestMap.put("1500Hz", listAudioFiles("audio/hearing_test/mask_left_ear/1500Hz/"));
        hearingTestMap.put("2000Hz", listAudioFiles("audio/hearing_test/mask_left_ear/2000Hz/"));
        hearingTestMap.put("3000Hz", listAudioFiles("audio/hearing_test/mask_left_ear/3000Hz/"));
        hearingTestMap.put("4000Hz", listAudioFiles("audio/hearing_test/mask_left_ear/4000Hz/"));
        hearingTestMap.put("6000Hz", listAudioFiles("audio/hearing_test/mask_left_ear/6000Hz/"));
        hearingTestMap.put("8000Hz", listAudioFiles("audio/hearing_test/mask_left_ear/8000Hz/"));
        hearingTestMap.put("12500Hz", listAudioFiles("audio/hearing_test/mask_left_ear/12500Hz/"));
        return hearingTestMap;
    }


    //右耳音频列表
    private Map<String, Object> rightEarFiles() {
        Map<String, Object> hearingTestMap = new HashMap<>();
        // 获取 right_ear 所有音频列表
        hearingTestMap.put("125Hz", listAudioFiles("audio/hearing_test/right_ear/125Hz/"));
        hearingTestMap.put("250Hz", listAudioFiles("audio/hearing_test/right_ear/250Hz/"));
        hearingTestMap.put("500Hz", listAudioFiles("audio/hearing_test/right_ear/500Hz/"));
        hearingTestMap.put("750Hz", listAudioFiles("audio/hearing_test/right_ear/750Hz/"));
        hearingTestMap.put("1000Hz", listAudioFiles("audio/hearing_test/right_ear/1000Hz/"));
        hearingTestMap.put("1500Hz", listAudioFiles("audio/hearing_test/right_ear/1500Hz/"));
        hearingTestMap.put("2000Hz", listAudioFiles("audio/hearing_test/right_ear/2000Hz/"));
        hearingTestMap.put("3000Hz", listAudioFiles("audio/hearing_test/right_ear/3000Hz/"));
        hearingTestMap.put("4000Hz", listAudioFiles("audio/hearing_test/right_ear/4000Hz/"));
        hearingTestMap.put("6000Hz", listAudioFiles("audio/hearing_test/right_ear/6000Hz/"));
        hearingTestMap.put("8000Hz", listAudioFiles("audio/hearing_test/right_ear/8000Hz/"));
        hearingTestMap.put("12500Hz", listAudioFiles("audio/hearing_test/right_ear/12500Hz/"));
        return hearingTestMap;
    }

    //右耳隐蔽音频列表
    private Map<String, Object> maskRightEar() {
        Map<String, Object> hearingTestMap = new HashMap<>();
        // 获取 right_ear 所有音频列表
        hearingTestMap.put("125Hz", listAudioFiles("audio/hearing_test/mask_right_ear/125Hz/"));
        hearingTestMap.put("250Hz", listAudioFiles("audio/hearing_test/mask_right_ear/250Hz/"));
        hearingTestMap.put("500Hz", listAudioFiles("audio/hearing_test/mask_right_ear/500Hz/"));
        hearingTestMap.put("750Hz", listAudioFiles("audio/hearing_test/mask_right_ear/750Hz/"));
        hearingTestMap.put("1000Hz", listAudioFiles("audio/hearing_test/mask_right_ear/1000Hz/"));
        hearingTestMap.put("1500Hz", listAudioFiles("audio/hearing_test/mask_right_ear/1500Hz/"));
        hearingTestMap.put("2000Hz", listAudioFiles("audio/hearing_test/mask_right_ear/2000Hz/"));
        hearingTestMap.put("3000Hz", listAudioFiles("audio/hearing_test/mask_right_ear/3000Hz/"));
        hearingTestMap.put("4000Hz", listAudioFiles("audio/hearing_test/mask_right_ear/4000Hz/"));
        hearingTestMap.put("6000Hz", listAudioFiles("audio/hearing_test/mask_right_ear/6000Hz/"));
        hearingTestMap.put("8000Hz", listAudioFiles("audio/hearing_test/mask_right_ear/8000Hz/"));
        hearingTestMap.put("12500Hz", listAudioFiles("audio/hearing_test/mask_right_ear/12500Hz/"));
        return hearingTestMap;
    }


    /**
     * 获取指定路径下的所有音频文件的URL列表。
     *
     * @param prefix 指定的路径前缀。
     * @return 包含所有音频文件URL的列表。
     */
    public static List<String> listAudioFiles(String prefix) {
        List<String> audioFileUrls = new ArrayList<>();

        // 初始化OSS客户端，并确保资源正确关闭
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            ObjectListing objectListing = ossClient.listObjects(
                    new ListObjectsRequest(BUCKET_NAME).withPrefix(prefix)
            );

            // 遍历所有文件并构建其完整URL
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                String audioFileUrl = DOMAIN + objectSummary.getKey();
                audioFileUrls.add(audioFileUrl);
            }
        } catch (Exception e) {
            // 异常处理：捕获并打印异常信息
            System.err.println("An error occurred: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 确保在异常发生时也能正确关闭OSSClient
            if (ossClient != null) {
                try {
                    ossClient.shutdown();
                } catch (Exception e) {
                    System.err.println("Failed to close OSSClient: " + e.getMessage());
                }
            }
        }

        return audioFileUrls;
    }
}
